package com.youxuan.service.impl;

import com.google.gson.Gson;
import com.youxuan.pojo.entity.ResponseFormat;
import com.youxuan.pojo.entity.ResponseResult;
import com.youxuan.service.GeneralService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class GeneralServiceImpl implements GeneralService {

    @Autowired
    UploadManager uploadManager;

    @Autowired
    String upToken;

//    @Value("${oss.prefix}")
//    String prefix;

    @Override
    public ResponseResult upload(MultipartFile file) {
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));
        int lastDot = file.getOriginalFilename().lastIndexOf(".");
        String type = file.getOriginalFilename().substring(lastDot);
        String key = format + file.hashCode()+type;

        DefaultPutRet putRet = null;
        try {
            InputStream inputStream = file.getInputStream();

            Response response = uploadManager.put(inputStream,key,upToken,null, null);
            //解析上传成功的结果

            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        } catch (Exception e) {
            e.printStackTrace();
        }


        ResponseFormat.UploadFormat uploadFormat = new ResponseFormat.UploadFormat();
        uploadFormat.setUrl(putRet.key);
        uploadFormat.setFileName(putRet.key);
        return ResponseResult.okResult(uploadFormat);
    }

}
